package com.atguigu.lease.web.app.service.impl;


import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.CodeUtil;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.mapper.UserInfoMapper;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.SmsService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.jsonwebtoken.Jwt;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private SmsService smsService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public void getCode(String phone) {
        //验证码的Key
        String codeKey = RedisConstant.APP_LOGIN_PREFIX +phone;

        //判断redis中是否有指定的codeKey
        Boolean result = stringRedisTemplate.hasKey(codeKey);
        //如果成立，表示该手机号发生过短信
        if (result){
            //获取验证码有效期还剩下多久
            Long expireTime = stringRedisTemplate.getExpire(codeKey);
            //验证码的过期总时长
            Integer totalTime = RedisConstant.APP_LOGIN_CODE_TTL_SEC;
            //判断是否是在1分钟内容发送的，如果是：向前端返回错误提示
            if (totalTime-expireTime<RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC){
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }


        //生成验证码                         验证码长度
        String code = CodeUtil.generateCode(6);

        //发送验证码
        smsService.getCode(phone,code);
        //redis保存验证码
        stringRedisTemplate.opsForValue().set(codeKey,code,RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);
    }

    @Override
    public String login(LoginVo loginVo) {

        String phone = loginVo.getPhone();
        String code = loginVo.getCode();

        String codeKey = RedisConstant.ADMIN_LOGIN_PREFIX+phone;
        //判断验证码是否正确
        if (!StringUtils.hasText(code)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
        //手机号不能为空
        if (!StringUtils.hasText(phone)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        //redis验证码是否过期
        String redisCode = stringRedisTemplate.opsForValue().get(codeKey);

        //查询数据库是否有对应手机号的用户信息
        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getPhone, phone));
        //如果没有则自动注册
        if (userInfo==null){
            userInfo= new UserInfo();
            //手机号赋值
            userInfo.setPhone(phone);
            //状态属性赋值
            userInfo.setStatus(BaseStatus.ENABLE);
            //昵称赋值                   截取手机号后5位
            userInfo.setNickname("用户-"+phone.substring(5));
            userInfoMapper.insert(userInfo);
        }
        //判断用户是否被禁用
        if (userInfo.getStatus()==BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }

        //生成token
        String tonken = JwtUtil.createTonken(userInfo.getId(), phone);
        //JwtUtil.parseToken():解析token




        return tonken;
    }

}



















